layui.use(['jquery', 'layer', 'table', 'upload', 'form'], function() {
	var $ = layui.$;
	var table = layui.table;
	var layer = layui.layer;
	var upload = layui.upload;
	var form = layui.form;
	var laydate = layui.laydate;
	var select_tr;

	var table_filter = 'importpk',
		where_json = {
			_o: 'pk_id',
			_b: 'desc',
		},
		form_filter = 'importpk_search_form';


	// 渲染表格
	if (load_data === true) {
		table.render({
			elem: '#' + table_filter,
			id: table_filter,
			url: importpk_list_url,
			method: 'post',
			height: 'full-238',
			where: where_json,
			cols: [importpk_cols],
			page: {
				layout: ['count', 'first', 'prev', 'page', 'next', 'last', 'skip'],
				limit: 30,
				theme: '#393d49',
				groups: 8
			},
			autoSort: false,
			toolbar: '#importpkToolbar',
			initSort: {
				field: 'pk_id',
				type: 'desc'
			}
		});
	}

	/* $('#exportpk').on('click', function() {
		console.log('导出')
		send_info(exportpk_url, {
			...where_json
		}, function(data) {
			layer.closeAll();
			layer.open({
				type: 2,
				title: '下载excel',
				content: data.data
			});
		})
	}) */

	upload.render({
		elem: '#implodePkd',
		url: upload_pkd,
		acceptMime: 'application/vnd.ms-excel',
		auto: true,
		accept: 'file',
		exts: 'xls',
		multiple: false,
		drag: false,
		before: function(obj) {
			layer.load();
		},
		done: function(res, index, upload) {
			if (res.code == 0) {
				layer.closeAll('loading');
				layer.confirm('导入成功，后台正在匹配，请耐心等待！', {
					icon: 3
				});
				return false;
			}
			table.reload('importpk')
			/* pkd_data_arr = res.data;
			$('.oprate-div').show();
			table.init('pikuan', {
				done: (r) => {
					let table = $('.layui-table-view[lay-id="pikuan"]').find(
						'table tbody')
					r.data.forEach((e, i) => {
						if (e.open > 0) {
							td = table.find('tr[data-index="' + i + '"]').find(
									'td:first').find('.laytable-cell-checkbox')
								.hide()
						}
					})
				}
			}) */
			layer.closeAll('loading');
		},
		error: function(index, upload) {
			layer.msg('excel格式错误', {
				icon: 2
			});
			layer.closeAll('loading');
		}
	});
	upload.render({
		elem: '#implodeXx',
		url: upload_xx,
		acceptMime: 'application/vnd.ms-excel',
		auto: true,
		accept: 'file',
		exts: 'xls',
		multiple: false,
		drag: false,
		before: function(obj) {
			layer.load();
		},
		done: function(res, index, upload) {
			if (res.code == 0) {
				layer.closeAll('loading');
				layer.msg(res.msg, {
					icon: 3
				});
				return false;
			} else {
				layer.closeAll('loading');
				layer.msg('导入成功', {
					icon: 1
				})

			}

		},
		error: function(index, upload) {
			layer.msg('excel格式错误', {
				icon: 2
			});
			layer.closeAll('loading');
		}
	});

	table.on('toolbar(' + table_filter + ')', function(obj) {
		switch (obj.event) {
			case 'allChenggong':
			case 'allDaiheshi':
				var checkStatus = table.checkStatus(table_filter);
				var check_flag = 1,
					id_arr = new Array();
				var data_state = $(this).attr('data-state');
				checkStatus.data.forEach((e, i) => {
					if (e.state != 0) {
						check_flag = 0
					}
					id_arr.push(e.pk_id)
				})
				if (check_flag != 1) {
					layer.msg('选择的数据存在不可操作！', {
						icon: 2
					})
					return false
				}
				if (id_arr.length == 0) {
					layer.msg('请选择操作数据', {
						icon: 2
					})
					return false
				}
				layer.confirm('确认操作码？', {
					icon: 3
				}, function() {
					send_info(renkuanmul_url, {
						data: id_arr,
						state: data_state
					}, function(data) {
						layer.msg('操作成功', {
							icon: 1
						})
						table.reload('importpk')
					})
				})

				break;
			case 'exportpk':
				send_info(exportpk_url, {
					...where_json
				}, function(data) {
					layer.closeAll();
					layer.open({
						type: 2,
						title: '下载excel',
						content: data.data
					});
				})
				break;
			case 'implodePkd':
				$('#implodePkd').click()
				break;
			case 'implodeXx':
				$('#implodeXx').click()
				break;
		}
	})

	form.on('select(order_level)', function(data) {
		order_level = data.value
	});

	const afterPikuan = (data) => {

		layer.confirm('匹款申请成功，后台正在匹配，请耐心等待！', {
			icon: 3
		}, function() {
			table.reload('importpk')
		})

	}

	// 匹款按钮
	$('.pikuan').on('click', function() {
		layer.confirm('是否开始匹款？', {
			icon: 3
		}, function() {
			let where = new Array()
			let times = $(this).attr('data-val')
			pkd_data_arr.forEach((e) => {
				if (e.open == 0) {
					let temp = {
						money: e.money,
						return_code: e.return_code,
						title: e.title,
					}
					where.push(temp)
				}
			})
			send_info(titlePikuan_url, {
				where,
				order_level,
				start_time,
				end_time,
				times,
				where_json
			}, function(data) {
				if (data.code != 0) {
					layer.msg(data.msg, {
						icon: 2
					})
					return false;
				}
				afterPikuan(data.data)
			})
		})

	})

	// 提交已操作的匹款信息
	$('#tijiao').on('click', () => {
		var post_data = pkd_data_arr.filter(value => value.state != -1)
		if (post_data.length == 0) {
			layer.msg('没有操作数据', {
				icon: 3
			})
		} else {
			layer.confirm('确认提交操作数据吗？', function(index) {
				send_info(renkuan_url, {
					post: post_data
				}, function(data) {
					pkd_data_arr = pkd_data_arr.filter(value => value.state == -1)
					table.init('pikuan', {
						done: (r) => {
							let table = $(
									'.layui-table-view[lay-id="pikuan"]')
								.find(
									'table tbody')
							r.data.forEach((e, i) => {
								if (e.open > 0) {
									td = table.find(
											'tr[data-index="' + i +
											'"]').find(
											'td:first').find(
											'.laytable-cell-checkbox'
										)
										.hide()
								}
							})
						}
					})
					layer.closeAll()
					layer.msg('提交成功', {
						icon: 1
					})
				})
			})
		}
	})

	// 设置手动认款状态
	$('#shoudong').on('click', () => {
		var checkStatus = table.checkStatus('pikuan');
		let post_data = checkStatus.data.filter((e) => {
			return e.open == 0
		})
		if (post_data.length == 0) {
			layer.msg('没有操作数据', {
				icon: 3
			})
		} else {

			layer.confirm('确认提交操作数据吗？', function(index) {
				var select_code = [];
				post_data.forEach((e) => {
					select_code.push(e.return_code)
				})
				console.log(select_code, '111')
				pkd_data_arr.forEach((e, i) => {
					if (select_code.indexOf(e.return_code) != -1) {
						pkd_data_arr[i].state = 0
					}
				})
				console.log(pkd_data_arr, '222')
				send_info(shoudong_url, {
					post: post_data
				}, function(data) {
					pkd_data_arr = pkd_data_arr.filter(value => value.state == -1)
					table.init('pikuan', {
						done: (r) => {
							let table = $(
									'.layui-table-view[lay-id="pikuan"]')
								.find(
									'table tbody')
							r.data.forEach((e, i) => {
								if (e.open > 0) {
									td = table.find(
											'tr[data-index="' + i +
											'"]').find(
											'td:first').find(
											'.laytable-cell-checkbox'
										)
										.hide()
								}
							})
						}
					})
					layer.closeAll()
					layer.msg('提交成功', {
						icon: 1
					})
				})
			})

		}
		console.log(post_data)
	})

	// 移除已匹配
	$('#yichu').on('click', () => {
		console.log('移除')
		pkd_data_arr = pkd_data_arr.filter(value => value.open == 0)
		table.init('pikuan', {
			done: (r) => {
				let table = $('.layui-table-view[lay-id="pikuan"]')
					.find('table tbody');
				r.data.forEach((e, i) => {
					if (e.open > 0) {
						td = table.find(
								'tr[data-index="' + i +
								'"]').find(
								'td:first').find(
								'.laytable-cell-checkbox'
							)
							.hide()
					}
				})
			}
		})
	})




	// 行工具事件
	table.on('tool(importpk)', function(obj) {
		var default_group = obj.data.default_group
		var return_code = obj.data.return_code
		var init_code = []
		switch (obj.event) {
			case "success":
				layer.confirm('确定操作吗？', {
					icon: 3,
					title: '温馨提示'
				}, function() {
					send_info(renkuan_url, {
						state: 1,
						pk_id: obj.data.pk_id
					}, function(data) {
						layer.closeAll()
						layer.msg('提交成功', {
							icon: 1
						})
						table.reload(table_filter)
						//obj.del()
					})
				})
				/* pkd_data_arr = pkd_data_arr.filter((value) => {
					if (value.return_code == return_code) {
						value.state = value.state == 1 ? -1 : 1
					} else {
						let chk_order = default_group.filter(order_no => order_no == value)
						if (chk_order.length > 0) {
							value.state = -1
							//value.default_group = []
							init_code.push(value.return_code)
						}
					}
					return value
				})
				obj.update({
					state: obj.data.state == 1 ? -1 : 1
				})
				if (obj.data.state == 1) {
					obj.tr.removeClass('select-success')
				} else {
					obj.tr.addClass('select-success')
				} */
				break;
			case "confirm":
				layer.confirm('确定操作吗？', {
					icon: 3,
					title: '温馨提示'
				}, function() {
					send_info(renkuan_url, {
						state: 3,
						pk_id: obj.data.pk_id
					}, function(data) {
						layer.closeAll()
						layer.msg('提交成功', {
							icon: 1
						})
						table.reload(table_filter)
						//obj.del()
					})
				})
				/* pkd_data_arr = pkd_data_arr.filter((value) => {
					if (value.return_code == return_code) {
						value.state = value.state == 0 ? -1 : 0
					} else {
						let chk_order = default_group.filter(order_no => order_no == value)
						if (chk_order.length > 0) {
							value.state = -1
							init_code.push(value.return_code)
							//value.default_group = []
						}
					}
					return value
				})
				obj.update({
					state: obj.data.state == 0 ? -1 : 0
				})
				if (obj.data.state == 0) {
					obj.tr.removeClass('select-wait')
				} else {
					obj.tr.addClass('select-wait')
				} */
				//table.init('pikuan', {})
				break;
			case "view":
				select_hkbh = obj.data.return_code
				send_info(viewOrder_url, {
					order_no_group: obj.data.order_no_group,
					pk_id: obj.data.pk_id
				}, function(res) {
					order_detail_arr = []
					if(res.code == 1){
						order_detail_arr.push(res.data);
					} else {
						obj.data.order_no_group.forEach((e, index) => {
							order_detail_arr[index] = res.data.filter((e1) => {
								if (e.indexOf(e1.out_order_no) != -1) {
									return e1
								}
							})
						})
					}
					console.log(order_detail_arr)
					var select_index = res.count
					select_tr = obj
					var tr = ''
					var order_state = [
						'无效订单号',
						'待确认',
						'待发货',
						'待支付',
						'待收货',
						'已完成',
						'已退货',
						'已取消',
						'待妥投',
						'已废止'
					]
					// 创建 表格内容
					order_detail_arr.forEach((e, i) => {
						e.forEach((e1, i1) => {
							let cart_td = ''
							e1.cart.forEach((e1, i1) => {
								cart_td += e1.fpmc + ';'
							})
							tr += '<tr>'
							if (i1 == 0) {
								if (select_index != i) {
									tr += `<td rowspan="${e.length}">
									<button type="button" class="layui-btn layui-btn-sm layui-btn-warm select-btn" data-i="${i}">选择</button>
									</td>`
								} else {
									tr += `<td rowspan="${e.length}">
									<button type="button" class="layui-btn layui-btn-sm layui-btn-success select-btn" data-i="${i}">已选</button>
									</td>`
								}
							}
							tr += `
							<td>${e1.contacts}</td>
							<td>${e1.phone}</td>
							<td>${e1.province + e1.city + e1.area + e1.street}</td>
							<td>${e1.out_order_no}</td>
							<td>${cart_td}</td>
							<td>${e1.huikuandanwei}</td>
							<td>${e1.company_name}</td>
							<td>${e1.yonghu_beizhu||'无'}</td>
							<td>${order_state[e1.jun_order_state]}</td>
							<td>${e1.order_money/100}</td>
							`
							tr += '</tr>'
						})

					})
					$('#order_info_box').html(tr)
					// 匹款信息列表
					var xx_list = ''
					res.msg.forEach((e) => {
						xx_list +=
							`<tr><td>${e.fkdw}</td><td>${e.address}</td><td>${e.phone}</td><td>${e.xxp}</td></tr>`
					})
					$('#pkxx_box').html(xx_list)
					layer.open({
						type: 1,
						shade: 0,
						offset: 'r',
						area: ['960px', '680px'],
						title: '匹配订单详情', //不显示标题
						content: $(
							'.order_info'
							), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
						cancel: function() {
							$('.order_info').hide();
						}
					}, function() {
						console.log('关闭')
					});
				})
				break;
			default:
				break;
		}
		if (init_code.length > 0) {
			layer.msg('以下回款编号已被重置：' + init_code, {
				icon: 2
			})
		}
	})

	// 获取当前时间
	let y = new Date().getFullYear(),
		m = new Date().getMonth() + 1,
		//sm = new Date().getMonth() + 1 - 6,
		d = new Date().getDate();
	let s_date = new Date();
	s_date = s_date.setMonth(s_date.getMonth() - 6)
	let s_date_ob = new Date(s_date)
	let sy = s_date_ob.getFullYear()
	let sm = s_date_ob.getMonth() + 1
	start_time = `${sy}-${sm<10?'0'+sm:sm}-${d<10?'0'+d:d}`
	end_time = `${y}-${m<10?'0'+m:m}-${d<10?'0'+d:d}`
	console.log(start_time, end_time)
	// 时间查询
	var pk_create_time_start = laydate.render({
		elem: 'input[name="pk_create_time_start"]',
		max: end_time,
		value: start_time,
		theme: '#393D49',
		done: function(value, date, endDate) {
			if (value) {
				start_time = value
				pk_create_time_end.config.min = {
					year: date.year,
					month: date.month - 1,
					date: date.date
				};
				pk_create_time_end.config.max = {
					year: date.year,
					month: date.month + 5,
					date: date.date
				};
			}

		}
	});
	var pk_create_time_end = laydate.render({
		elem: 'input[name="pk_create_time_end"]',
		max: end_time,
		value: end_time,
		min: start_time,
		theme: '#393D49',
		done: function(value, date, endDate) {
			if (value) {
				pk_create_time_end.config.max = {
					year: date.year,
					month: date.month - 1,
					date: date.date
				};
				end_time = value
			}

		}
	});

	$('#order_info_box').on('click', '.select-btn', function() {
		console.log(select_tr)
		console.log($(this).attr('data-i'))
		let index = $(this).attr('data-i'),
			get_default_group = select_tr.data.order_no_group[index];

		if (get_default_group != select_tr.data.default_group) {
			select_tr.update({
				default_group: get_default_group
			})

			send_info(updateSelect_url, {
				pk_id: select_tr.data.pk_id,
				default_group: get_default_group
			}, function() {
				layer.msg('设置默认成功', {
					icon: 1
				});
				//select_tr.del()
			})
		}
		/* var default_index = $(this).attr('data-i')
		pkd_data_arr = pkd_data_arr.filter((val) => {
			if (val.return_code == select_hkbh) {
				val.default_group = val.order_no_group[default_index]
				val.runs = 1
				select_tr.update({
					default_group: val.default_group,
					runs: 1,
					state: 1
				})
				select_tr.tr.addClass('select-success')
			}
			return val
		}) */

		//table.init('pikuan', {})
		layer.closeAll()
	})

	// 下面开始查询处理
	// 排序
	table.on('sort(' + table_filter + ')', function(data) {
		var _o = data.field;
		var _b = data.type;
		table.reload(table_filter, {
			initSort: data,
			where: {
				_o: _o,
				_b: _b
			}
		})
	})

	// 回款时间
	var pay_time_start_1 = laydate.render({
		elem: '#pay_time_start_1',
		max: 1,
		theme: '#393D49',
		done: function(value, date, endDate) {
			if (value) {
				pay_time_end_1.config.min = {
					year: date.year,
					month: date.month - 1,
					date: date.date
				};
			}
			where_json['pay_time_start'] = value;
		}
	});
	var pay_time_end_1 = laydate.render({
		elem: '#pay_time_end_1',
		max: 1,
		theme: '#393D49',
		done: function(value, date, endDate) {
			if (value) {
				pay_time_start_1.config.max = {
					year: date.year,
					month: date.month - 1,
					date: date.date
				};
			}
			where_json['pay_time_end'] = value;
		}
	});

	form.render();

	// 表单input 查询
	$('form[lay-filter="' + form_filter + '"]').on('input propertychange', 'input[type="text"]', function() {
		if ($(this).prop('comStart')) return;
		var value = $(this).val();
		var name = $(this).attr('name');
		where_json[name] = value;
	}).on('compositionstart', 'input[type="text"]', function() {
		$(this).prop('comStart', true);
	}).on('compositionend', 'input[type="text"]', function() {
		$(this).prop('comStart', false);
		$(this).trigger('input');
	});

	form.on('select', function(data) {
		console.log(data)
		if (data.elem.attributes['lay-filter'].value == 'order_level_search') {
			where_json['order_level'] = data.value;
		} else if (data.elem.attributes['lay-filter'].value != 'order_level') {
			where_json[data.elem.attributes['lay-filter'].value] = data.value;
		}

	})



	form.on('submit(importpk_search_form)', function(data) {
		layer.load();
		table.reload(table_filter, {
			where: where_json,
			page: {
				curr: 1
			},
			done: function(res, curr, count) {
				layer.closeAll();
				//layuiRowspanChakuan(res.data,['pk_id', 'return_code', 'pay_time','create_time','title','money','state','zhiyi_state','oprate','zhiyi_order','reject_reason']);
			}
		});
		return false
	})

})